<?php

namespace app\admin\model\shop;

use think\Model;
use traits\model\SoftDelete;

/**
 * sku商品插件
 */
class SkuGoods extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'jeek_shop_sku_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'price'
    ];
    
    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    // 获取商品价格区间
    public function getPriceAttr($v,$d)
    {
        $specProduct = new SkuProduct();
        $list = $specProduct->where('goods_id',$d['id'])->order('price','asc')->column('price');
        $len = count($list);
        if($len == 1) return $list[0];
        return $list[0] == $list[$len-1]?$list[0]:$list[0].'~'.$list[$len-1];
    }

    /**
     * 一对一关联分类
     *
     * @return void
     */
    public function category()
    {   
        return $this->belongsTo('app\common\model\Category','category_id')->setEagerlyType(0);
    }
}
